﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;

using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevTeam;

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows.Forms;


namespace ConfExpert.Forms.Siparisler
{
    public partial class _YuklemeFormlari : XForm
    {
        int CustomerId;
        public _YuklemeFormlari(int CustomerId)
        {
            InitializeComponent();
            this.CustomerId = CustomerId;
            //TAM.YuklemeGidenTableAdapter = new Datasets.MyDataTableAdapters.YuklemeGidenTableAdapter();
        }

        private void YuklemeFormlari_Load(object sender, EventArgs e)
        {


            //gridView1.Init("GetYuklemeFormlari", CustomerId);

            BindingSource bs = new BindingSource(ds, "YuklemeGiden");
            AddBsToList(bs);
            InitGridView(gridView1, bs);
            InitBands();

            gridView1.Columns["PaymentMethodId"].ColumnEdit = RI(Rp.PaymentMethodS);

            GridManager gm = GridManager.GetManager(gridView1);
            gm.GridMenu.AddMenu("Excelde Göster", ExceldeGoster);


            gridView1.SetCaptions(
            "YuklemeGidenId:#",
            "UserId:Müşteri Temsilcisi",
            "IhracatciFirma:İhracatçı Firma",
            "UreticiFirma:Üretici Firma",
            "UrunYuklemeTarihi:Ürün Yükleme Tarihi",
            "FaturaAdresi:Adres Satırı 1",
            "FaturaAdresi2:Adres Satırı 2",
            "FPostalCode:Posta Kodu",
            "FCity:Şehir",
            "FCountryId:Ülke",
            "FKontakKisi:Kontak Kişi",
            "FTel:Tel",
            "FFax:Fax",
            "FEMail:Email",
            "TeslimatAdresi:Adres Satırı 1",
            "TeslimatAdresi2:Adres Satırı 2",
            "TPostalCode:Posta Kodu",
            "TCity:Şehir",
            "TCountryId:Ülke",
            "TKontakKisi:Kontak Kişi",
            "TTel:Tel",
            "TFax:Fax",
            "TEMail:Email",
            "MusterininBankaIsmi:İsmi",
            "BankaTelNo:Tel No",
            "BankaFaxNo:Fax No",
            "HesapNumarasi:Hesap No",
            "IbanNo:IBAN No",
            "SwiftCodeNo:SWIFT Code No",
            "VergiNo:Vergi No",
            "PaymentTermId:Ödeme Vadesi",
            "PaymentMethodId:Ödeme Şekli",
            "LC_AkreditifNo:LC (akreditif) No",
            "OdemeNotu:Ödeme Notu",
            "ShipMethodId:Yükleme Şekli",
            "TeslimSekliSId:Teslim Şekli",
            "NakliyeciAdi:Adı",
            "NakliyeciAddress:Adresi",
            "NakliyeciTelNo:Tel No",
            "NakliyeciFaxNo:Fax No",
            "NakliyeciEmail:Email",
            "NakliyeciKontakKisi:Kontak Kişi",
            "KoliOlcusu:Koli Ölçüsü",
            "KoliKaclik:Koli Kaçlık",
            "AskiliGomlekAdet:Askılı Gömlek Adedi",
            "NumuneOnayiBekleniyorMu:NumuneOnayiBekleniyorMu",
            "MusteriInspectionVarMi:MusteriInspectionVarMi",
            "OzelNotlar:Özel Notlar");

            GetDetails("YuklemeGiden", "GetYuklemeGiden", CustomerId);

            RepositoryItemMemoExEdit mex = new DevExpress.XtraEditors.Repository.RepositoryItemMemoExEdit();
            mex.ShowIcon = false;
            mex.ScrollBars = ScrollBars.Vertical;
            mex.PopupFormMinSize = new System.Drawing.Size(750, 400);

            gridView1.Columns["OzelNotlar"].ColumnEdit = mex;
            //gv.Columns["AnsweredBy"].ColumnEdit = RI(Rp.V_User);

            //gv.MakeColumnInvisible("Screenshot", "Form", "App", "isResolved");
            //gv.YanYanaGetir_Soluna("AnsweredBy", "ErrorMsg", "Notlar");

            gridView1.AddSummary();
            gridView1.BestFitColumns();
            gridView1.Columns["OzelNotlar"].Width = 360;
            barButtonItem1.ItemClick += barButtonItem1_ItemClick;
            //gridView1.CustomDrawFooterCell += gridView1_CustomDrawFooterCell;

        }

        private void ExceldeGoster(object sender, EventArgs e)
        {
            DataRow dr = this.gridView1.GetFocusedDataRow();

            DataTable t = ExecuteDataTable("GetForms", dr["FormType"]);
            FileToSend = ByteArrayToFile3(t.Rows[0]["Name"].ToString() + t.Rows[0]["FileExtension"], t.Rows[0]["File"] as byte[]);

            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(FileToSend);
            SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets[0];
            SpreadsheetGear.IRange cells = workbook.Worksheets[0].Cells;

            SpreadsheetGear.INames names = workbook.Names;
            foreach (SpreadsheetGear.IName n in names)
            {
                switch (n.Name)
                {
                    case "InsertedOn": cells[n.Name].Value = dr["InsertedOn"]; break;
                }
            }

            //names.Add("Jan", "='2005 Sales'!$B$2:$B$4");
            //names.Add("Feb", "='2005 Sales'!$C$2:$C$4");
            //names.Add("Mar", "='2005 Sales'!$D$2:$D$4");
            //names.Add("Sales", "='2005 Sales'!$B$2:$D$4");
            //// Format sales data as currency.
            //cells["Sales"].NumberFormat = "$#,##0";



            cells[2, 1].Value = dr["InsertedOn"];

            cells[5, 1].Value = AppSession.Lookups.V_Customer.FindByCustomerId(intParse(dr["CustomerId"])).Name;
            cells[6, 1].Value = dr["UserId"].ToString() == "" ? "" : AppSession.Lookups.V_User.FindByUserId(intParse(dr["UserId"])).Username;
            cells[8, 1].Value = dr["UrunYuklemeTarihi"];

            cells[11, 1].Value = dr["FaturaAdresi"];
            cells[12, 1].Value = dr["FaturaAdresi2"];
            cells[13, 1].Value = dr["FPostalCode"];
            cells[14, 1].Value = dr["FCity"];
            cells[15, 1].Value = dr["FCountryId"].ToString() == "" ? "" : AppSession.Lookups.Country.FindByCountryId(intParse(dr["FCountryId"])).Name;

            cells[17, 1].Value = dr["FKontakKisi"];
            cells[18, 1].Value = dr["FTel"];
            cells[19, 1].Value = dr["FFax"];
            cells[20, 1].Value = dr["FEMail"];

            cells[23, 1].Value = dr["TeslimatAdresi"];
            cells[24, 1].Value = dr["TeslimatAdresi2"];
            cells[25, 1].Value = dr["TPostalCode"];
            cells[26, 1].Value = dr["TCity"];
            cells[27, 1].Value = dr["TCountryId"].ToString() == "" ? "" : AppSession.Lookups.Country.FindByCountryId(intParse(dr["TCountryId"])).Name;

            cells[29, 1].Value = dr["TKontakKisi"];
            cells[30, 1].Value = dr["TTel"];
            cells[31, 1].Value = dr["TFax"];
            cells[32, 1].Value = dr["TEMail"];


            string numune = "";
            string musInsp = "";

            if (dr["NumuneOnayiBekleniyorMu"].ToString() == "True")
                numune = "Evet";
            else if (dr["NumuneOnayiBekleniyorMu"].ToString() == "False")
                numune = "Hayır";

            if (dr["MusteriInspectionVarMi"].ToString() == "True")
                musInsp = "Evet";
            else if (dr["MusteriInspectionVarMi"].ToString() == "False")
                musInsp = "Hayır";


            if (t.Rows[0]["Name"].ToString() == "İHRACAT YÜKLEME FORMU")
            {
                cells[7, 1].Value = dr["IhracatciFirma"];

                cells[35, 1].Value = dr["MusterininBankaIsmi"];
                cells[36, 1].Value = dr["BankaTelNo"];
                cells[37, 1].Value = dr["BankaFaxNo"];
                cells[38, 1].Value = dr["HesapNumarasi"];
                cells[39, 1].Value = dr["IbanNo"];
                cells[40, 1].Value = dr["SwiftCodeNo"];
                cells[41, 1].Value = dr["VergiNo"];

                cells[43, 1].Value = dr["PaymentTermId"];
                cells[44, 1].Value = dr["PaymentMethodId"];
                cells[46, 1].Value = dr["LC_AkreditifNo"];
                cells[48, 1].Value = dr["OdemeNotu"];

                cells[51, 1].Value = dr["ShipMethodId"].ToString() == "" ? "" : AppSession.Lookups.ShipMethod.FindByShipMethodId(intParse(dr["ShipMethodId"])).Name;
                cells[52, 1].Value = dr["TeslimSekliSId"].ToString() == "" ? "" : AppSession.Lookups.TeslimSekliS.FindByTeslimSekliSId(intParse(dr["TeslimSekliSId"])).Name;

                cells[57, 1].Value = dr["NakliyeciAdi"];
                cells[58, 1].Value = dr["NakliyeciAddress"];
                cells[59, 1].Value = dr["NakliyeciTelNo"];
                cells[60, 1].Value = dr["NakliyeciFaxNo"];
                cells[61, 1].Value = dr["NakliyeciEmail"];
                cells[62, 1].Value = dr["NakliyeciKontakKisi"];

                cells[66, 1].Value = dr["KoliOlcusu"];
                cells[67, 1].Value = dr["KoliKaclik"];
                cells[68, 1].Value = dr["AskiliGomlekAdet"];

                cells[72, 1].Value = numune;
                cells[73, 1].Value = musInsp;

                cells[76, 1].Value = dr["OzelNotlar"];
            }
            else
            {
                cells[7, 1].Value = dr["UreticiFirma"];

                cells[36, 1].Value = dr["PaymentTermId"];
                cells[37, 1].Value = dr["PaymentMethodId"];
                cells[39, 1].Value = dr["OdemeNotu"];

                cells[40, 1].Value = dr["VergiNo"];

                cells[47, 1].Value = dr["ShipMethodId"].ToString() == "" ? "" : AppSession.Lookups.ShipMethod.FindByShipMethodId(intParse(dr["ShipMethodId"])).Name;
                cells[48, 1].Value = dr["TeslimSekliSId"].ToString() == "" ? "" : AppSession.Lookups.TeslimSekliS.FindByTeslimSekliSId(intParse(dr["TeslimSekliSId"])).Name;

                cells[53, 1].Value = dr["NakliyeciAdi"];
                cells[54, 1].Value = dr["NakliyeciAddress"];
                cells[55, 1].Value = dr["NakliyeciTelNo"];
                cells[56, 1].Value = dr["NakliyeciFaxNo"];
                cells[57, 1].Value = dr["NakliyeciEmail"];
                cells[58, 1].Value = dr["NakliyeciKontakKisi"];

                cells[62, 1].Value = dr["KoliOlcusu"];
                cells[63, 1].Value = dr["KoliKaclik"];
                cells[64, 1].Value = dr["AskiliGomlekAdet"];

                cells[69, 1].Value = numune;
                cells[70, 1].Value = musInsp;

                cells[73, 1].Value = dr["OzelNotlar"];
            }

            string FileName = FileToSend;
            workbook.SaveAs(FileName, SpreadsheetGear.FileFormat.OpenXMLWorkbook);
            FileManager.RunFile(FileName);


        }

        string FileToSend;
        public string ByteArrayToFile3(string filePath, byte[] content)
        {
            string FullPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache) + "\\" + filePath;
            using (FileStream fs = new FileStream(FullPath, FileMode.Create, FileAccess.Write))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    bw.Write(content);
                    bw.Flush();
                }
            }

            return FullPath;
        }



        //void gridView1_CustomDrawFooterCell(object sender, FooterCellCustomDrawEventArgs e)
        //{
        //    if (e.Column != null
        //        && e.Column.SummaryItem != null
        //        && e.Column.SummaryItem.SummaryType == SummaryItemType.Count)
        //    {
        //        e.Info.DisplayText = ((double)e.Info.Value).ToString("#,##0") + " records";
        //    }
        //}

        void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Save();
        }

        Dictionary<string, GridBand> bands = new Dictionary<string, GridBand>();

        void InitBands()
        {
            gridView1.Bands.Clear();
            gridView1.Images = bgvIcons;

            int idx = 0;
            foreach (string str in "Yüklemeye Özel;Fatura Bilgileri;Teslimat Bilgileri;Banka;Ödeme ve Yükleme Şekli;Nakliyeci;Diğer".Split(";".ToCharArray()))
            {
                GridBand band = gridView1.Bands.AddBand(str);
                band.ImageIndex = (idx++) % 6;
                bands.Add(str, band);
            }

            foreach (string colName in "YuklemeGidenId,InsertedOn,UserId,CustomerId,IhracatciFirma,UrunYuklemeTarihi".Split(','))
                bands["Yüklemeye Özel"].Columns.Add(gridView1.Columns[colName]);

            foreach (string colName in "FaturaAdresi,FaturaAdresi2,FPostalCode,FCity,FCountryId,FKontakKisi,FTel,FFax,FEmail".Split(','))
                bands["Fatura Bilgileri"].Columns.Add(gridView1.Columns[colName]);

            foreach (string colName in "TeslimatAdresi,TeslimatAdresi2,TPostalCode,TCity,TCountryId,TKontakKisi,TTel,TFax,TEmail".Split(','))
                bands["Teslimat Bilgileri"].Columns.Add(gridView1.Columns[colName]);

            foreach (string colName in "MusterininBankaIsmi,BankaTelNo,BankaFaxNo,HesapNumarasi,IbanNo,SwiftCodeNo,VergiNo".Split(','))
                bands["Banka"].Columns.Add(gridView1.Columns[colName]);

            foreach (string colName in "PaymentTermId,PaymentMethodId,LC_AkreditifNo,OdemeNotu,ShipMethodId,TeslimSekliSId".Split(','))
                bands["Ödeme ve Yükleme Şekli"].Columns.Add(gridView1.Columns[colName]);

            foreach (string colName in "NakliyeciAdi,NakliyeciAddress,NakliyeciTelNo,NakliyeciFaxNo,NakliyeciEmail,NakliyeciKontakKisi".Split(','))
                bands["Nakliyeci"].Columns.Add(gridView1.Columns[colName]);

            foreach (string colName in "KoliOlcusu,KoliKaclik,AskiliGomlekAdet,NumuneOnayiBekleniyorMu,MusteriInspectionVarMi,OzelNotlar".Split(','))
                bands["Diğer"].Columns.Add(gridView1.Columns[colName]);

            //gridView1.AddSummary();
            gridView1.Bands[0].Columns[0].Summary.Add(DevExpress.Data.SummaryItemType.Count, "YuklemeGidenId", "{0:#,##0} records");
            //gridView1.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            //gridView1.Columns[0].SummaryItem.DisplayFormat = "{0:#,##0} records";
        }


    }
}
